<?php

namespace App\Http\Controllers\Api;

use App\V3\Api\Models\AnnounceModel;
use App\Helper\DBRSAUtil;
use App\Helper\Utils\Util;
use App\Http\Controllers\Controller;
use App\Models\LogInstorageModel;
use App\Models\MaterielClassModel;
use App\Models\MaterielTypeModel;
use App\Models\StorageManageModel;
use App\Models\StorageModel;
use App\Models\SystemConfigModel;
use App\Services\StorageManageService;
use App\V3\Api\Models\StorageShelfLocationModel;
use App\V3\Api\Models\StorageShelfModel;
use App\V3\V3_2_7\Models\AdminAddendumModel;
use App\V3\V3_2_7\Models\LocationLogModel;
use App\V3\V3_2_7\Models\VipSettingModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use OSS\OssClient;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Illuminate\Support\Facades\File;
use App\V3\Api\Models\StorageBatchModel;
use App\Models\AdminModel;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use App\V3\Api\Services\SellService;
use App\Services\CommonService;
use App\V3\V3_2_7\Services\LogService;
use Illuminate\Validation\Rule;
use App\V3\V3_2_7\Services\BarterService;
use App\V3\V3_2_7\Services\MaterielService;
use App\V3\V3_2_7\Services\OverflowBreakageService;

class CommonController extends Controller
{
    protected $ossClient;

    public function __construct(Request $request)
    {
        $this->ossClient = new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
        );
    }

    public function generateBarcode()
    {
//        return 'zs'.date('YmdHis').mt_rand(1000, 9999);
        $time = time();
        $barcode = new BarcodeGenerator();
        $text = 'zs' . date('YmdHis') . mt_rand(1000, 9999);
        $barcode->setText($text);
        $barcode->setType(BarcodeGenerator::Code128);
        $barcode->setScale(2);
        $barcode->setThickness(25);
        $barcode->setFontSize(10);

        $path = public_path() . '/barcode/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
        File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);

        $barcode->setFormat('png');
        $barcode->setFilename($path . $text . '.png');
        $barcode->generate();

        return response()->json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'barcode_url' => '/barcode/' . date('Y') . '/' . date('m') . '/' . date('d') . '/' . $text . '.png'
            ]
        ]);
    }

    /**
     * 百度api开放平台-识别地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author ソンブ
     * @created_at: 2022/2/17 17:29
     */
    public function readAddress(Request $request)
    {
        if (!empty($content = $request->input('content'))) {

            $client = new \AipNlp(
                config('app.bd_api_id'),
                config('app.bd_api_key'),
                config('app.bd_secret_key')
            );

            $data = $client->address($content);
            if (empty($data)) {
                return response()->json(
                    ['code' => 1, 'msg' => '识别失败！', 'data' => $data]
                );
            }
            $data['name'] = $data['person'];
            $data['mobile'] = $data['phonenum'];
            $data['address'] = $data['province'] . $data['city'] . $data['county'] . $data['town'] . $data['detail'];

            return response()->json(
                ['code' => 0, 'msg' => 'success', 'data' => $data]
            );
        } else {
            return response()->json(
                ['code' => 0, 'msg' => 'success', 'data' => '']
            );
        }
    }

    /**
     * 导出excel-库存
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/7/30 11:34
     * @return array|void
     */
    public function export(Request $request)
    {
        $data = $request->all();
        if (empty($data['token'])) {
            return ['code' => 1, 'msg' => 'token验证失败，请重新登录', 'data' => ''];
        }
        $array = explode(' ', $data['token']);

        //获取导出的数据
        $exportData = StorageManageService::exportData($array[0], $data);
//        if(empty($exportData)) {
//            return response()->json(['code' => 1,'msg' => '无可用数据可供导出','data' => '']);
//        }

        @ini_set('memory_limit', '1024M');
        @ini_set('max_execution_time', 30);
        ob_end_clean();
        ob_start();
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $spreadsheet->getDefaultStyle();
        $sheet->setTitle('库存导出报表');

        //A1-L1字体加粗
        $spreadsheet->getActiveSheet()->getStyle('A1:M1')->getFont()->setBold(true);
        //设置字体
        $spreadsheet->getDefaultStyle()->getFont()->setName('宋体');
        //设置字体大小
        $spreadsheet->getDefaultStyle()->getFont()->setSize(12);
        //设置默认行高
        $spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(40);

        $spreadsheet->getActiveSheet()->getStyle('A:M')->getAlignment()->setHorizontal('center');
        $spreadsheet->getActiveSheet()->getStyle('A:M')->getAlignment()->setVertical('center');

        //设置列宽
        $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('J')->setWidth(40);
        $spreadsheet->getActiveSheet()->getColumnDimension('K')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('L')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('M')->setWidth(20);

        $sheet->setCellValue('A1', '商品图')
            ->setCellValue('B1', '商品编号')
            ->setCellValue('C1', '商品名')
            ->setCellValue('D1', '商品型号')
            ->setCellValue('E1', '商品一级分类名')
            ->setCellValue('F1', '商品一级分类编号')
            ->setCellValue('G1', '商品二级分类名')
            ->setCellValue('H1', '商品二级分类编号')
            ->setCellValue('I1', '仓库名')
            ->setCellValue('J1', '仓库地址')
            ->setCellValue('K1', '商品成本')
            ->setCellValue('L1', '库存数')
            ->setCellValue('M1', '备注');

        //设置自动换行
        $spreadsheet->getActiveSheet()->getStyle('B')->getAlignment()->setWrapText(true);
        $spreadsheet->getActiveSheet()->getStyle('C')->getAlignment()->setWrapText(true);
        $spreadsheet->getActiveSheet()->getStyle('D')->getAlignment()->setWrapText(true);
        $spreadsheet->getActiveSheet()->getStyle('E')->getAlignment()->setWrapText(true);
        $spreadsheet->getActiveSheet()->getStyle('F')->getAlignment()->setWrapText(true);
        $spreadsheet->getActiveSheet()->getStyle('G')->getAlignment()->setWrapText(true);
        $spreadsheet->getActiveSheet()->getStyle('H')->getAlignment()->setWrapText(true);
        $spreadsheet->getActiveSheet()->getStyle('I')->getAlignment()->setWrapText(true);
        $spreadsheet->getActiveSheet()->getStyle('J')->getAlignment()->setWrapText(true);
        $spreadsheet->getActiveSheet()->getStyle('M')->getAlignment()->setWrapText(true);

        foreach ($exportData as $key => $value) {
            $key += 2;
            if (!empty($value['materiel_img'])) {
                $imgPath = public_path() . $value['materiel_img'];
                if (!file_exists($imgPath)) {
                    $sheet->setCellValue('A' . $key, '');
                } else {
                    $fileInfo = pathinfo($imgPath);

                    //过滤非文件类型
                    if (!empty($fileInfo['basename'])) {
                        $drawing[$key] = new Drawing();
                        $drawing[$key]->setResizeProportional(false);
                        $drawing[$key]->setName('商品图');
                        $drawing[$key]->setDescription('商品图');
                        $drawing[$key]->setPath($imgPath);
                        $drawing[$key]->setWidth(40);
                        $drawing[$key]->setHeight(40);
                        $drawing[$key]->setOffsetX(10);
                        $drawing[$key]->setOffsetY(10);
                        $drawing[$key]->setCoordinates('A' . $key);
                        $drawing[$key]->setWorksheet($sheet);
                    }
                }
            } else {
                $sheet->setCellValue('A' . $key, '');
            }

            $sheet->setCellValue('B' . $key, $value['materiel_no'])
                ->setCellValue('C' . $key, $value['materiel_name'])
                ->setCellValue('D' . $key, $value['type_name'])
                ->setCellValue('E' . $key, $value['f_class_name'])
                ->setCellValue('F' . $key, $value['f_class_no'])
                ->setCellValue('G' . $key, $value['s_class_name'])
                ->setCellValue('H' . $key, $value['s_class_no'])
                ->setCellValue('I' . $key, $value['storage_name'])
                ->setCellValue('J' . $key, $value['storage_address'])
                ->setCellValue('K' . $key, $value['materiel_mean_cost'])
                ->setCellValue('L' . $key, $value['in_storage_num'])
                ->setCellValue('M' . $key, $value['remark']);
        }

        return SELF::downloadExcel($request, $spreadsheet, '库存报表_' . date('Y-m-d'), 'Xlsx');
    }

    //实现对excel的下载
    private function downloadExcel($request, $spreadsheet, $filename, $format)
    {
        if ($format == 'Xlsx') {
            $contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        } else if ($format == 'Xls') {
            $contentType = 'application/vnd.ms-excel';
        }

        $filenameUrl = $filename . '.' . strtolower($format);
        $objWriter = IOFactory::createWriter($spreadsheet, $format);
        //保存到服务器临时文件下
        $objWriter->save('./tmp.xlsx');
        //删除临时文件
        unlink('./tmp.xlsx');

        header('Content-Type: ' . $contentType . '; charset=utf-8');    //输出文件类型
        header('Content-Disposition: attachment;filename="' . $filenameUrl . '"');    //输出文件名
        header('Cache-Control: max-age=0');    //强制每次请求直接发送给源服务器，而不经过本地缓存版本的校验
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');

        //清空
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit;
    }

    public function import(Request $request)
    {
        @ini_set('max_execution_time', 10000000);
        @ini_set('memory_limit', '256M');//只限于当前脚本临时修改内存大小
        set_time_limit(300);

        //token校验
        $token = $request->header('token');
        if (empty($token)) {
            echo json_encode([
                'code' => 2,
                'msg' => 'token获取失败',
                'data' => '',
            ], JSON_UNESCAPED_UNICODE);
            die;
        }

        $files = $request->file('import_templete');//获取上传文件

        if (empty($files)) {
            return response()->json([
                'code' => 1,
                'msg' => '请选择要上传的文件',
                'data' => ''
            ]);
        }

        //获取文件拓展名
        $ext = $files->extension();

        if ($files->getSize() > 10 * 1024 * 1024) {
            return response()->json([
                'code' => 1,
                'msg' => '文件大小不能超出10M',
                'data' => ''
            ]);
        }

        $time = time();

        //application/vnd.ms-excel  为xls或xlsx文件类型
        if (!in_array($ext, ['xls', 'xlsx'])) {
            $ext = $files->clientExtension();
            if (!in_array($ext, ['xls', 'xlsx'])) {
                return response()->json([
                    'code' => 1,
                    'msg' => '必须为excel表格，且必须为xlsx或xls格式！',
                    'data' => ''
                ]);
            }
        }

        //私钥获取-解析token
        $array = explode(' ', $token);
        $private = SystemConfigModel::getConfigValue('private');
        $rsadata = DBRSAUtil::rsaDecrypt($array[1], $private);
        $rsadata = json_decode($rsadata, true);
        /* $rsadata['mainUserId']=6588;
        $rsadata['userId']=6588; */
        $adminInfo = \App\Api\Models\AdminModel::where('id', $rsadata['mainUserId'])->first();

        //读取excel文件内容
        if ($ext == 'xls') {
            $reader = IOFactory::createReader('Xls');
        } else if ($ext == 'xlsx') {
            $reader = IOFactory::createReader('Xlsx');
        }

        $path = $files->store(date('Y') . '/' . date('m') . '/' . date('d'));
        $filePath = public_path() . '/uploads/' . $path;

        $objSpreadsheet = $reader->load($filePath);
        $objWorksheet = $objSpreadsheet->getSheet(0);//读取第一个工作表
        $highestRow = $objWorksheet->getHighestRow();       // 取得总行数
        $data = $objWorksheet->toArray();
        //图片导入处理
        if (!empty((array)$objWorksheet->getDrawingCollection())) {
            foreach ($objWorksheet->getDrawingCollection() as $drawing) {
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                $imgFileName = $drawing->getIndexedFileName();
                if ($drawing instanceof MemoryDrawing) {
                    ob_start();
                    call_user_func(
                        $drawing->getRenderingFunction(),
                        $drawing->getImageResource()
                    );
                    $imageContents = ob_get_contents();
                    ob_end_clean();
                    switch ($drawing->getMimeType()) {
                        case MemoryDrawing::MIMETYPE_PNG :
                            $extension = 'png';
                            break;
                        case MemoryDrawing::MIMETYPE_GIF:
                            $extension = 'gif';
                            break;
                        case MemoryDrawing::MIMETYPE_JPEG :
                            $extension = 'jpg';
                            break;
                    }
                } else {
                    $zipReader = fopen($drawing->getPath(), 'r');
                    $imageContents = '';
                    while (!feof($zipReader)) {
                        $imageContents .= fread($zipReader, 2048);
                    }
                    fclose($zipReader);
                    $extension = $drawing->getExtension();

                    if (in_array($drawing->getExtension(), ['jpg', 'jpeg', 'png'])) {
                        $imgPath = public_path() . '/uploads/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';

                        switch ($drawing->getExtension()) {
                            case 'jpg':
                            case 'jpeg':
                                $source = imagecreatefromjpeg($drawing->getPath());
                                imagejpeg($source, $imgPath . $imgFileName);
                                break;
                            case 'png':
                                $imgType = substr($imgFileName, -4);
                                if ($imgType != '.png') {
                                    $imgFileName .= '.png';
                                }

                                $source = @imagecreatefrompng($drawing->getPath());
                                imagepng($source, $imgPath . $imgFileName);
                                break;
                        }

                        $startColumn = SELF::ABC2decimal($startColumn);
                        $cutImgPath = explode('public', $imgPath);

                        $data[$startRow - 1][$startColumn] = $cutImgPath[1] . $imgFileName;
                    }
                    $c = $drawing->getCoordinates();
                    preg_match_all('!\d+!', $c, $matches);
                    $column = $matches[0][0];
                    $row = strstr($c, $column, true);
                    file_put_contents($imgPath . $imgFileName, $imageContents);
                }
            }
        }
        //验证是否为空表
        if (count($data) > 1) {
            unset($data[0]); //去掉首行
        } else {
            unlink($filePath);
            return fail('', '表数据不能为空！');
        }
        unlink($filePath);

        //数组分块处理
        $chunck = collect($data);
        $chunks = $chunck->chunk(100);
        $chunks->all();
        //开启事务，可以不用事务，因为有更新功能
        DB::beginTransaction();
        try {
            $client = $this->ossClient;
            $imgInfo = [];
            $smData = [];
            $logInfo = [];
            $storageManageArr = [];
            $imgUrlArr = [];
            $goodsData = [];
            foreach ($chunks->toArray() as $cVal) {
                foreach ($cVal as $key => $value) {
                    if (!empty($value[2]) && !empty($value[4])) {
                        $value = array_slice($value, 0, 15);
                        $imgUrl = '';
                        if (stripos($value[0], 'upload') !== false) {
                            $imgInfo[] = public_path() . $value[0];
                            $client->uploadFile(config('app.aliyun_oss_bucket'), ltrim($value[0], './'), public_path() . $value[0]);
                            $imgUrl = config('app.aliyun_oss_bucket_url') . $value[0];
                            $imgUrlArr[] = $imgUrl;
                        }

                        if (empty($value[2])) {
                            throw new \Exception('商品名不能为空');
                        }

                        //商品成本验证
                        if (!empty($value[11])) {
                            if (!is_numeric(trim($value[11]))) {
                                throw new \Exception('商品成本只能为数字');
                            }
                            if (trim($value[11]) < 0) {
                                throw new \Exception('商品成本最小只能为0');
                            }
                        } else {
                            $value[11] = 0;
                        }

                        //库存数验证
                        if (!empty($value[12])) {
                            if (!is_numeric($value[12])) {
                                throw new \Exception('库存数只能为数字');
                            }
                            if ($value[12] < 0) {
                                throw new \Exception('库存数最小只能为0');
                            }
                        } else {
                            $value[12] = 0;
                        }

                        //销售价验证
                        if (!empty($value[9])) {
                            if (!is_numeric($value[9])) {
                                throw new \Exception('销售价只能为数字');
                            }
                            if ($value[9] < 0) {
                                throw new \Exception('销售价最小只能为0');
                            }
                        } else {
                            $value[9] = 0;
                        }

                        //最低销售价验证
                        if (!empty($value[10])) {
                            if (!is_numeric($value[9])) {
                                throw new \Exception('最低销售价只能为数字');
                            }
                            if ($value[10] < 0) {
                                throw new \Exception('最低销售价最小只能为0');
                            }
                        } else {
                            $value[10] = 0;
                        }

                        $isProductOrGoods = empty($value[14]) ? 0 : $value[14];

                        if (!in_array($isProductOrGoods, [0, 1])) {
                            throw new \Exception('商品/套餐标记不合法');
                        }

                        //唯一条件是什么，需了解业务
                        $storageManageInfo = StorageManageModel::select(
                            'a.*',
                        )->from('storage_manage as a')
                            ->leftJoin('materiel_class as b', 'b.id', '=', 'a.materiel_class_id')
                            ->leftJoin('materiel_class as c', 'c.id', '=', 'b.parent_id')
                            ->leftJoin('materiel_type as d', 'd.id', '=', 'a.type_id')
                            ->where([
                                'c.class_name' => empty($value[5]) ? '默认一级' : $value[5],
                                'materiel_class_name' => empty($value[6]) ? '默认二级' : $value[6],
                                'd.materiel_name' => $value[2],
                                'd.type_name' => empty($value[3]) ? '' : $value[3],
                                'd.materiel_no' => empty($value[1]) ? '' : $value[1],
                                'a.main_id' => $rsadata['mainUserId'],
                                'storage_name' => empty($value[4]) ? '默认仓库' : $value[4],
                                'a.delete_flag' => 0,
                                'd.is_product_materiel' => $isProductOrGoods
                            ])
                            ->first();
                        if (!empty($storageManageInfo)) {
                            //更新已有的数据
                            $divisor = ($storageManageInfo['materiel_mean_cost'] * $storageManageInfo['in_storage_num'])
                                +
                                (trim($value[11]) * $value[12]);
                            if ($divisor == 0) {
                                $meanPirce = 0;
                            } else {
                                $price = $storageManageInfo['in_storage_num'] + $value[12];

                                if ($price == 0) {
                                    $meanPirce = 0;
                                } else {
                                    $meanPirce = sprintf("%.2f",
                                        (
                                            ($storageManageInfo['materiel_mean_cost'] * $storageManageInfo['in_storage_num'])
                                            +
                                            (trim($value[11]) * $value[12])
                                        )
                                        / $price);
                                }
                            }
                            $storageManageArr[] = [
                                'id' => $storageManageInfo['id'],
                                'in_storage_num' => $storageManageInfo['in_storage_num'] + $value[12],
                                //'virtual_storage_num' => $storageManageInfo['virtual_storage_num'] + $value[12],
                            ];

                            $goodsData[] = [
                                'id' => $storageManageInfo['type_id'],
                                'materiel_no' => empty($value[1]) ? '' : $value[1],
                                'selling_price' => empty($value[9]) ? 0 : $value[9],
                                'lower_selling_price' => empty($value[10]) ? 0 : $value[10],
                                'bar_code' => empty($value[8]) ? 0 : $value[8],
                                'materiel_unit' => empty($value[7]) ? '' : $value[7],
                                'is_product_materiel' => empty($value[14]) ? '' : $value[14],
                                'cost' => $meanPirce,
                                'materiel_img' => empty($imgUrl) ? '' : $imgUrl,
                                'materiel_thumbnail_img' => $imgUrl . config('app.aliyun_oss_thumbnail_url'),
                            ];
                            $logInfo[] = [
                                'type' => 2,
                                'storage_id' => $storageManageInfo['storage_id'],
                                'storage_name' => $storageManageInfo['storage_name'],
                                'storage_address' => $storageManageInfo['storage_address'],
                                'curr_storage_manage_id' => $storageManageInfo['id'],
                                'batch_id' => '',
                                'materiel_class_id' => $storageManageInfo['materiel_class_id'],
                                'materiel_class_name' => $storageManageInfo['class_name'],
                                'materiel_class_no' => $storageManageInfo['class_no'],
                                'materiel_type_id' => $storageManageInfo['type_id'],
                                'type_name' => $storageManageInfo['type_name'],
                                'materiel_name' => $storageManageInfo['materiel_name'],
                                'materiel_no' => $storageManageInfo['materiel_no'],
                                'operate_num' => $value[12],
                                'last_storage_num' => $storageManageInfo['in_storage_num'],
                                'next_storage_num' => $storageManageInfo['in_storage_num'] + $value[12],
                                'materiel_mean_cost' => $meanPirce,
                                'user_id' => $rsadata['userId'],
                                'main_id' => $rsadata['mainUserId'],
                                'shelf_id' => $storageManageInfo['shelf_id'],
                                'location_id' => $storageManageInfo['location_id'],
                                'in_storage_time' => $time,
                                'remark' => '库存导入',
                                'created_at' => $time
                            ];
                        } else {
                            //写入新记录
                            $logInfo[] = SELF::newStorageInfo($value, $rsadata['userId'], $rsadata['mainUserId'], $imgUrl, $time);
                        }
                    }
                }
            }
            LogInstorageModel::insert($logInfo);
            if (!empty($storageManageArr)) {
                batch()->update(new StorageManageModel, $storageManageArr, 'id');
            }
            if (!empty($goodsData)) {
                batch()->update(new MaterielTypeModel(), $goodsData, 'id');
            }
            $data['main_id'] = $rsadata['mainUserId'];
            $data['user_id'] = $rsadata['userId'];
            /*   $logData = '导入商品信息，共'.count($data).'条';
               CommonService::log('库存导入报表', $data, $logData);*/
            //获取上传的图片大小
            $fileSize = 0;
            foreach ($imgInfo as $val) {
                $fileSize += filesize($val);
            }
            //更新可用存储空间
            $result = saveFileSize(['main_id' => $rsadata['mainUserId']], $fileSize, []);
            if ($result['code'] != 0) {
                throw new \Exception($result['msg']);
            }
            //清除本地图片
            foreach (array_unique($imgInfo) as $v1) {
                unlink($v1);
            }
            DB::commit();
            return success();
        } catch (\Exception $e) {
            Log::debug('库存导入异常' . var_export($data, true));
            DB::rollBack();
            if (!empty($imgInfo)) {
                foreach ($imgInfo as $v1) {
                    unlink($v1);
                }
                foreach ($imgUrlArr as $v2) {
                    $client->deleteObject(config('app.aliyun_oss_bucket'), ltrim($v2, $v2[0]));
                }
            }

            return fail('', $e->getMessage());
        }
    }

    public function import_no_product(Request $request)
//    public function import(Request $request)
    {
        @ini_set('max_execution_time', '10000');
        $token = $request->header('token');
        if (empty($token)) {
            echo json_encode([
                'code' => 2,
                'msg' => 'token获取失败',
                'data' => '',
            ], JSON_UNESCAPED_UNICODE);
            die;
        }
        $array = explode(' ', $token);
        //私钥获取
        $private = SystemConfigModel::getConfigValue('private');
        $rsadata = DBRSAUtil::rsaDecrypt($array[1], $private);
        $rsadata = json_decode($rsadata, true);

        $adminInfo = \App\Api\Models\AdminModel::where('id', $rsadata['mainUserId'])->first();

        $files = $request->file('import_templete');

        $time = time();

        if (empty($files)) {
            return response()->json([
                'code' => 1,
                'msg' => '请选择要上传的文件',
                'data' => ''
            ]);
        }
        //$ext = $files->clientExtension();
        $ext = $files->extension();

        if ($files->getSize() > 10 * 1024 * 1024) {
            return response()->json([
                'code' => 1,
                'msg' => '文件大小不能超出10M',
                'data' => ''
            ]);
        }

        //application/vnd.ms-excel  为xls或xlsx文件类型
        if (!in_array($ext, ['xls', 'xlsx'])) {
            $ext = $files->clientExtension();
            if (!in_array($ext, ['xls', 'xlsx'])) {
                return response()->json([
                    'code' => 1,
                    'msg' => '必须为excel表格，且必须为xlsx或xls格式！',
                    'data' => ''
                ]);
            }
        }

        if ($ext == 'xls') {
            $reader = IOFactory::createReader('Xls');
        } else if ($ext == 'xlsx') {
            $reader = IOFactory::createReader('Xlsx');
        }

        $path = $files->store(date('Y') . '/' . date('m') . '/' . date('d'));
        $filePath = public_path() . '/uploads/' . $path;

        $objSpreadsheet = $reader->load($filePath);
        $objWorksheet = $objSpreadsheet->getSheet(0);//读取第一个工作表
//        $highestColumn = $excelSheet->getHighestColumn();   // 取得总列数
        $highestRow = $objWorksheet->getHighestRow();       // 取得总行数
        /*  echo "<pre>";
         var_dump($highestRow);die; */
        $data = $objWorksheet->toArray();

        foreach ($data as $kk => $dataValue) {
            if (empty($dataValue[2]) && empty($dataValue[8])) {
                unset($data[$kk]);
            }
        }

        if (!empty((array)$objWorksheet->getDrawingCollection())) {
            foreach ($objWorksheet->getDrawingCollection() as $drawing) {
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());

                $imgFileName = $drawing->getIndexedFileName();

                if ($drawing instanceof MemoryDrawing) {
                    ob_start();
                    call_user_func(
                        $drawing->getRenderingFunction(),
                        $drawing->getImageResource()
                    );
                    $imageContents = ob_get_contents();
                    ob_end_clean();
                    switch ($drawing->getMimeType()) {
                        case MemoryDrawing::MIMETYPE_PNG :
                            $extension = 'png';
                            break;
                        case MemoryDrawing::MIMETYPE_GIF:
                            $extension = 'gif';
                            break;
                        case MemoryDrawing::MIMETYPE_JPEG :
                            $extension = 'jpg';
                            break;
                    }
                } else {
                    $zipReader = fopen($drawing->getPath(), 'r');
                    $imageContents = '';
                    while (!feof($zipReader)) {
                        $imageContents .= fread($zipReader, 2048);
                    }
                    fclose($zipReader);
                    $extension = $drawing->getExtension();

                    if (in_array($drawing->getExtension(), ['jpg', 'jpeg', 'png'])) {
                        $imgPath = public_path() . '/uploads/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';

                        switch ($drawing->getExtension()) {
                            case 'jpg':
                            case 'jpeg':
                                $source = imagecreatefromjpeg($drawing->getPath());
                                imagejpeg($source, $imgPath . $imgFileName);
                                break;
                            case 'png':
                                $imgType = substr($imgFileName, -4);
                                if ($imgType != '.png') {
                                    $imgFileName .= '.png';
                                }

                                $source = imagecreatefrompng($drawing->getPath());
                                imagepng($source, $imgPath . $imgFileName);
                                break;
                        }

                        $startColumn = SELF::ABC2decimal($startColumn);
                        $cutImgPath = explode('public', $imgPath);

                        $data[$startRow - 1][$startColumn] = $cutImgPath[1] . $imgFileName;
                    }

                    $c = $drawing->getCoordinates();
                    preg_match_all('!\d+!', $c, $matches);
                    $column = $matches[0][0];
                    $row = strstr($c, $column, true);

                    file_put_contents($imgPath . $imgFileName, $imageContents);

//旧有代码
//            if(in_array($drawing->getExtension(), ['jpg', 'jpeg', 'png'])) {
//                switch($drawing->getExtension()) {
//                    case 'jpg':
//                    case 'jpeg':
//                        $source = imagecreatefromjpeg($drawing->getPath());
//                        imagejpeg($source, $imgPath.$imgFileName);
//                        break;
//                    case 'png':
//                        $imgFileName .= '.png';
//                        $source = imagecreatefrompng($drawing->getPath());
//                        imagepng($source, $imgPath.$imgFileName);
//                        break;
//                }
//                $startColumn = SELF::ABC2decimal($startColumn);
//                $cutImgPath = explode('public', $imgPath);
//
//                $data[$startRow -1][$startColumn] = $cutImgPath[1].$imgFileName;
//            }
                }
            }
        }

        unset($data[0]);
        unlink($filePath);

        DB::beginTransaction();

        try {
            $client = $this->ossClient;
            $imgInfo = [];
            $smData = [];
            $logInfo = [];
            $storageManageArr = [];
            foreach ($data as $key => $value) {
                $value = array_slice($value, 0, 14);

                $imgUrlArr = [];
                $imgUrl = '';
                if (stripos($value[0], 'upload')) {
                    $imgInfo[] = public_path() . $value[0];

                    $client->uploadFile(config('app.aliyun_oss_bucket'), ltrim($value[0], './'), public_path() . $value[0]);

                    $imgUrl = config('app.aliyun_oss_bucket_url') . $value[0];

                    $imgUrlArr[] = $imgUrl;
                }

                if (empty($value[2])) {
                    return SELF::returnJson(1, '商品名不能为空', '', $data);
                }
//                if(empty($value[3])) {
//                    return SELF::returnJson(1, '规格名不能为空', '', $data);
//                }
                if (!empty($value[11])) {
                    if (!is_numeric(trim($value[11]))) {
                        return SELF::returnJson(1, '商品成本只能为数字', '', $data);
                    }
                    if (trim($value[11]) < 0) {
                        return SELF::returnJson(1, '商品成本最小只能为0', '', $data);
                    }
                } else {
                    $value[11] = 0;
                }
                if (!empty($value[12])) {
                    if (!is_numeric($value[12])) {
                        return SELF::returnJson(1, '库存数只能为数字', '', $data);
                    }
                    if ($value[12] < 0) {
                        return SELF::returnJson(1, '库存数最小只能为0', '', $data);
                    }
                } else {
                    $value[12] = 0;
                }
//
//                $storageManageInfo = StorageManageModel::getInfo(
//                    empty($value[6])?'默认二级':$value[6],
//                    $value[2],
//                    empty($value[3])?'':$value[3],
//                    empty($value[4])?'默认仓库':$value[4],
//                    $rsadata['mainUserId'],
//                );

                $storageManageInfo = StorageManageModel::select(
                    'a.*',
                )->from('storage_manage as a')
                    ->leftJoin('materiel_class as b', 'b.id', '=', 'a.materiel_class_id')
                    ->leftJoin('materiel_class as c', 'c.id', '=', 'b.parent_id')
                    ->where([
                        'c.class_name' => empty($value[5]) ? '默认一级' : $value[5],
                        'materiel_class_name' => empty($value[6]) ? '默认二级' : $value[6],
                        'materiel_name' => $value[2],
                        'type_name' => empty($value[3]) ? '' : $value[3],
                        'materiel_no' => empty($value[1]) ? '' : $value[1],
                        'a.main_id' => $rsadata['mainUserId'],
                        'storage_name' => empty($value[4]) ? '默认仓库' : $value[4],
                        'a.delete_flag' => 0
                    ])
                    ->first();

                if (!empty($storageManageInfo)) {

                    $divisor = ($storageManageInfo['materiel_mean_cost'] * $storageManageInfo['in_storage_num'])
                        +
                        (trim($value[11]) * $value[12]);
                    if ($divisor == 0) {
                        $meanPirce = 0;
                    } else {
                        $price = $storageManageInfo['in_storage_num'] + $value[12];

                        if ($price == 0) {
                            $meanPirce = 0;
                        } else {
                            $meanPirce = sprintf("%.2f",
                                (
                                    ($storageManageInfo['materiel_mean_cost'] * $storageManageInfo['in_storage_num'])
                                    +
                                    (trim($value[11]) * $value[12])
                                )
                                / $price);
                        }

                    }

                    $storageManageArr[] = [
                        'id' => $storageManageInfo['id'],
                        'in_storage_num' => $storageManageInfo['in_storage_num'] + $value[12],
                        'virtual_storage_num' => $storageManageInfo['virtual_storage_num'] + $value[12],
                    ];

//                    StorageManageModel::where('id', $storageManageInfo['id'])
//                        ->update([
//                            'in_storage_num' => $storageManageInfo['in_storage_num'] + $value[12],
//                            'virtual_storage_num' => $storageManageInfo['virtual_storage_num'] + $value[12],
//                            'materiel_mean_cost' => $meanPirce,
//                        ]);

                    /*   $smData[]=[
                          'id'=>$storageManageInfo['id'],
                          'in_storage_num' => $storageManageInfo['in_storage_num'] + $value[11],
                          'virtual_storage_num' => $storageManageInfo['virtual_storage_num'] + $value[11],
                          'materiel_mean_cost' => $meanPirce,
                          'delete_flag' => 0
                      ]; */

                    $materielTypeInfo = MaterielTypeModel::where('id', $storageManageInfo['type_id'])->first();

                    if (!empty($materielTypeInfo['materiel_img'])) {

                        $isHttpStart = substr($materielTypeInfo['materiel_img'], 0, 4);

                        if ($isHttpStart != 'http') {
                            if (file_exists(public_path() . $materielTypeInfo['materiel_img'])) {
                                unlink(public_path() . $materielTypeInfo['materiel_img']);
                            }
                        } else {
                            $substrUrl = explode('uploads', $materielTypeInfo['materiel_img']);

                            $client->deleteObject(config('app.aliyun_oss_bucket'), 'uploads' . $substrUrl[1]);
                        }
                    }

                    $materielTypeInfo->materiel_no = empty($value[1]) ? '' : $value[1];
                    $materielTypeInfo->selling_price = empty($value[9]) ? 0 : $value[9];
                    $materielTypeInfo->lower_selling_price = empty($value[10]) ? 0 : $value[10];
                    $materielTypeInfo->bar_code = empty($value[8]) ? 0 : $value[8];
                    $materielTypeInfo->materiel_unit = empty($value[7]) ? '' : $value[7];
                    $materielTypeInfo->cost = $meanPirce;
                    $materielTypeInfo->materiel_img = empty($imgUrl) ? '' : $imgUrl;
                    $materielTypeInfo->remark = empty($value[13]) ? '' : $value[13];
                    $materielTypeInfo->materiel_thumbnail_img = $imgUrl . config('app.aliyun_oss_thumbnail_url');
                    $materielTypeInfo->save();

                    $batchNo = $adminInfo['batch_title'] . date('YmdHis', time()) . mt_rand(1000, 9999) . '0';

                    do {
                        $batchNo = $adminInfo['batch_title'] . date('YmdHis', time()) . mt_rand(1000, 9999) . '0';
                    } while (!empty(StorageBatchModel::where('main_id', $rsadata['mainUserId'])
                        ->where('batch_no', $batchNo)->first()));

                    $batchId = SELF::createBatchInfo(
                        $batchNo,
                        $storageManageInfo['id'],
                        $meanPirce,
                        $value[12],
                        0,
                        $rsadata['mainUserId']
                    );

                    $logInfo[] = [
                        'type' => 2,
                        'storage_id' => $storageManageInfo['storage_id'],
                        'storage_name' => $storageManageInfo['storage_name'],
                        'storage_address' => $storageManageInfo['storage_address'],
                        'curr_storage_manage_id' => $storageManageInfo['id'],
                        'batch_id' => $batchId,
                        'materiel_class_id' => $storageManageInfo['materiel_class_id'],
                        'materiel_class_name' => $storageManageInfo['class_name'],
                        'materiel_class_no' => $storageManageInfo['class_no'],
                        'materiel_type_id' => $storageManageInfo['type_id'],
                        'type_name' => $storageManageInfo['type_name'],
                        'materiel_name' => $storageManageInfo['materiel_name'],
                        'materiel_no' => $storageManageInfo['materiel_no'],
                        'operate_num' => $value[12],
                        'last_storage_num' => $storageManageInfo['in_storage_num'],
                        'next_storage_num' => $storageManageInfo['in_storage_num'] + $value[12],
                        'materiel_mean_cost' => $meanPirce,
                        'user_id' => $rsadata['userId'],
                        'main_id' => $rsadata['mainUserId'],
                        'shelf_id' => $storageManageInfo['shelf_id'],
                        'location_id' => $storageManageInfo['location_id'],
                        'in_storage_time' => $time,
                        'remark' => '库存导入',
                        'created_at' => $time
                    ];
                } else {
                    $logInfo[] = SELF::newStorageInfo($value, $rsadata['userId'], $rsadata['mainUserId'], $imgUrl, $time);
                }
            }

            LogInstorageModel::insert($logInfo);

            if (!empty($storageManageArr)) {
                batch()->update(new StorageManageModel, $storageManageArr, 'id');
            }

            //获取上传的图片大小
            $fileSize = 0;
            foreach ($imgInfo as $val) {
                $fileSize += filesize($val);
            }

            //更新可用存储空间
            $result = saveFileSize(['main_id' => $rsadata['mainUserId']], $fileSize, []);

            if ($result['code'] != 0) {
                throw new \Exception($result['msg']);
            }

            //清除本地图片
            foreach ($imgInfo as $v1) {
                unlink($v1);
            }

            DB::commit();
            return SELF::returnJson();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('库存导入异常' . var_export($data, true));
            if (!empty($imgInfo)) {
                foreach ($imgInfo as $v1) {
                    unlink($v1);
                }

                foreach ($imgUrlArr as $v2) {

                    $client->deleteObject(config('app.aliyun_oss_bucket'), ltrim($v2, $v2[0]));
                }
            }
            return SELF::returnJson(1, $e->getMessage(), '');
        }
    }

    public function ABC2decimal($abc)
    {
        $ten = 0;
        $len = strlen($abc);

        for ($i = 1; $i <= $len; $i++) {
            $char = substr($abc, 0 - $i, 1);
            $int = ord($char);
            $ten += ($int - 65) * pow(26, $i - 1);
        }

        return $ten;
    }

    private function returnJson($code = 0, $msg = 'success', $data = '')
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    private function newStorageInfo($data, $userId, $mainId, $imgUrl, $time)
    {
        $materielTypeData = [];
        //检查商品一级分类是否存在
        $firstClassData = MaterielClassModel::query()
            ->select('id', 'class_no')
            ->where([
                'class_name' => empty($data[5]) ? '默认一级' : $data[5],
                'parent_id' => 0,
                'main_id' => $mainId,
                'is_product_class' => 0,
                'delete_flag' => 0
            ])->first();

        if (empty($firstClassData)) {
            $firstClassNo = Util::randStr(4);
            while (MaterielClassModel::query()->where([
                'class_no' => $firstClassNo,
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->exists()) {
                $firstClassNo = Util::randStr(4);
            }

            $secondClassNo = Util::randStr(4);
            while (MaterielClassModel::query()->where([
                'class_no' => $secondClassNo,
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->exists()) {
                $secondClassNo = Util::randStr(4);
            }

            //一级分类信息
            $firstClassData['class_name'] = empty($data[5]) ? '默认一级' : $data[5];
            $firstClassData['parent_id'] = 0;
            $firstClassData['class_no'] = $firstClassNo;
            $firstClassData['main_id'] = $mainId;
            $firstClassData['created_at'] = time();
            $newFirstClassId = MaterielClassModel::insertGetId($firstClassData);
            //二级分类信息
            $secondClassData['class_name'] = empty($data[6]) ? '默认二级' : $data[6];
            $secondClassData['parent_id'] = $newFirstClassId;
            $secondClassData['class_no'] = $secondClassNo;
            $secondClassData['full_class_no'] = $firstClassNo . $secondClassNo;
            $secondClassData['main_id'] = $mainId;
            $secondClassData['created_at'] = time();

            $newSecondClassId = MaterielClassModel::insertGetId($secondClassData);
            $secondClassData['id'] = $newSecondClassId;
        } else {
            //检查物料二级分类是否存在
            $secondClassData = MaterielClassModel::where([
                'class_name' => empty($data[6]) ? '默认二级' : $data[6],
                'parent_id' => $firstClassData['id'],
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->first();

            $secondClassNo = Util::randStr(4);

            while (MaterielClassModel::query()->where([
                'class_no' => $secondClassNo,
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->exists()) {
                $secondClassNo = Util::randStr(4);
            }

            if (empty($secondClassData)) {
                //二级分类信息
                $secondClassData['class_name'] = empty($data[6]) ? '默认二级' : $data[6];
                $secondClassData['parent_id'] = $firstClassData['id'];
                $secondClassData['class_no'] = $secondClassNo;
                $secondClassData['full_class_no'] = $firstClassData['class_no'] . $secondClassNo;
                $secondClassData['main_id'] = $mainId;
                $secondClassData['created_at'] = time();

                $newSecondClassId = MaterielClassModel::insertGetId($secondClassData);
                $secondClassData['id'] = $newSecondClassId;
            } else {
                //检查商品信息
                $materielTypeData = MaterielTypeModel::where([
                    'materiel_class_id' => $secondClassData['id'],
                    'materiel_no' => $data[1],
                    'materiel_name' => $data[2],
                    'type_name' => empty($data[3]) ? '' : $data[3],
                    'is_product_materiel' => $data[14],
                    'main_id' => $mainId,
                    'delete_flag' => 0
                ])->first();
            }
        }

        if (empty($materielTypeData)) {
            $materielNo = Util::randStr(8);
            while (MaterielTypeModel::query()->where([
                'materiel_no' => $materielNo,
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->exists()) {
                $materielNo = Util::randStr(8);
            }
            $materielTypeData['materiel_img'] = $imgUrl;
            $materielTypeData['materiel_thumbnail_img'] = $imgUrl . config('app.aliyun_oss_thumbnail_url');
            $materielTypeData['bar_code'] = empty($data[8]) ? '' : $data[8];
            $materielTypeData['materiel_unit'] = empty($data[7]) ? '' : $data[7];
            $materielTypeData['materiel_name'] = $data[2];
            $materielTypeData['selling_price'] = empty($data[9]) ? 0 : $data[9];
            $materielTypeData['lower_selling_price'] = empty($data[10]) ? 0 : $data[10];
            $materielTypeData['type_name'] = empty($data[3]) ? '' : $data[3];
            $materielTypeData['materiel_no'] = empty($data[1]) ? $materielNo : $data[1];
            $materielTypeData['materiel_class_id'] = $secondClassData['id'];
            $materielTypeData['remark'] = empty($data[13]) ? '' : $data[13];
            $materielTypeData['is_product_materiel'] = empty($data[14]) ? '' : $data[14];
            $materielTypeData['main_id'] = $mainId;
            $materielTypeData['created_at'] = time();
            $materielTypeData['cost'] = empty($data[11]) ? '' : $data[11];
            $newMaterielId = MaterielTypeModel::insertGetId($materielTypeData);
            $materielTypeData['id'] = $newMaterielId;
        }

        $data['storage_name'] = !isset($data[4]) ? '默认仓库' : $data[4];
        //检查仓库信息
        $storageData = StorageModel::where([
            'storage_name' => $data['storage_name'],
            'main_id' => $mainId,
            'delete_flag' => 0
        ])->first();

        if (empty($storageData)) {
            $storageData['storage_name'] = empty($data[4]) ? '默认仓库' : $data[4];
            $storageData['storage_address'] = '';
            $storageData['user_id'] = $mainId;
            $storageData['main_id'] = $mainId;
            $storageData['remarks'] = '';
            $storageData['created_at'] = time();

            $newStorageId = StorageModel::insertGetId($storageData);
            $storageData['id'] = $newStorageId;

            $storageData['shelf_id'] = StorageShelfModel::insertGetId([
                'shelf_name' => '默认货架',
                'main_id' => $mainId,
                'storage_id' => $newStorageId,
                'created_at' => time(),
                'shelf_type' => 1
            ]);

            $storageData['location_id'] = StorageShelfLocationModel::insertGetId([
                'location_name' => '默认库位',
                'main_id' => $mainId,
                'storage_id' => $newStorageId,
                'created_at' => time(),
                'location_type' => 1,
                'shelf_id' => $storageData['shelf_id'],
            ]);
        } else {
            $shelfId = StorageShelfModel::where([
                'storage_id' => $storageData['id'],
                'shelf_type' => 1
            ])->first();
            $storageData['shelf_id'] = $shelfId['id'];
            $shelfLocationId = StorageShelfLocationModel::where([
                'storage_id' => $storageData['id'],
                'shelf_id' => $shelfId['id'],
                'location_type' => 1
            ])->first();
            $storageData['location_id'] = $shelfLocationId['id'];
        }
        $smId = StorageManageModel::insertGetId([
            'materiel_class_id' => $secondClassData['id'],
            'materiel_class_name' => $secondClassData['class_name'],
            'materiel_class_no' => $secondClassData['class_no'],
            'type_id' => $materielTypeData['id'],
            'materiel_name' => $materielTypeData['materiel_name'],
            'type_name' => $materielTypeData['type_name'],
            'materiel_no' => $materielTypeData['materiel_no'],
            'storage_id' => $storageData['id'],
            'storage_name' => $storageData['storage_name'],
            'storage_address' => $storageData['storage_address'],
            'in_storage_num' => $data['12'],
            //'virtual_storage_num' => $data['12'],
            'materiel_mean_cost' => $data['11'],
            'main_id' => $mainId,
            'shelf_id' => $storageData['shelf_id'],
            'location_id' => $storageData['location_id'],
//                'remark' => $data[13],
            'in_storage_time' => $time,
            'created_at' => $time
        ]);

        return [
            'type' => 2,
            'storage_id' => $storageData['id'],
            'storage_name' => $storageData['storage_name'],
            'storage_address' => $storageData['storage_address'],
            'curr_storage_manage_id' => $smId,
            'batch_id' => '',
            'materiel_class_id' => $secondClassData['id'],
            'materiel_class_name' => $secondClassData['class_name'],
            'materiel_class_no' => $secondClassData['class_no'],
            'materiel_type_id' => $materielTypeData['id'],
            'type_name' => $materielTypeData['type_name'],
            'materiel_name' => $materielTypeData['materiel_name'],
            'materiel_no' => $materielTypeData['materiel_no'],
            'operate_num' => $data[12],
            'last_storage_num' => 0,
            'next_storage_num' => $data[12],
            'materiel_mean_cost' => $data[11],
            'user_id' => $mainId,
            'main_id' => $mainId,
            'in_storage_time' => time(),
            'remark' => '库存导入',
            'created_at' => time(),
            'shelf_id' => $storageData['shelf_id'],
            'location_id' => $storageData['location_id'],
        ];
    }

    public function download()
    {
        ob_end_clean();
        $headers = [
            'Content-Type: application/xlsx',
        ];
        return response()->download(public_path() . '/storage_templete.xlsx', 'storage_templete.xlsx', $headers);
    }

    public function readBatch(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'batch_no' => 'required',//条码信息
            'code_type' => 'required',
        ], [
            'batch_no.required' => '参数`条码信息`缺失',
            'code_type.required' => '参数`码的类型`缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json(['code' => 1, 'msg' => $info, 'data' => '']);
        }

        return response()->json(
            \App\Api\Services\StorageManageService::readBatchNo($data)
        );
    }

    public function createBatchInfo($batchNo, $storageManageId, $cost, $num, $materielId, $mainId)
    {
        return StorageBatchModel::insertGetId([
            'batch_no' => $batchNo,
            'storage_manage_id' => $storageManageId,
            'batch_num' => $num,
            'batch_left_num' => $num,
            'batch_cost' => $cost,
            'materiel_id' => $materielId,
            'main_id' => $mainId,
            'created_at' => time()
        ]);
    }

    /**
     * 最新公告
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/14 18:25
     * @return \Illuminate\Http\JsonResponse
     */
    public function newAnnounce()
    {
        return response()->json([
            'code' => 0,
            'msg' => 'success',
            'data' => AnnounceModel::where('is_publish', 1)->where('delete_flag', 0)->first()
        ]);
    }

    public function getMainAccount(Request $request)
    {
        if (!empty($request->input('id'))) {
            $adminInfo = AdminModel::select(
                'b.username'
            )
                ->from('admin as a')
                ->leftJoin('admin as b', 'a.parent_id', '=', 'b.id')
                ->where('a.id', $request->input('id'))
                ->first();

            return $adminInfo['username'];
        }

        return response()->json([
            'code' => 1,
            'msg' => '你在查什么，死鬼',
            'data' => ''
        ]);
    }

    public function getLogInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//操作日志类型;0:入库;1:出库;
        ], [
            'id.required' => '日志id为缺失',
            'type.required' => '参数`日志类型`缺失',
            'type.in' => '参数`日志类型`不合法'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(
            [
                'code' => 0,
                'msg' => 'success',
                'data' => LogService::detail($data)
            ]
        );
    }

    /**
     * 退换货单详细
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2023/11/9 17:04
     * @return \Illuminate\Http\JsonResponse
     */
    public function barterDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required',//换货单主键id
        ], [
            'id.required' => '参数`换货单id`缺失'
        ]);

        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(BarterService::detail($request->id));
    }

    /**
     * 采购货单详细
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2023/11/27 17:04
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMaterielInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required',//采购单主键id
        ], [
            'id.required' => '参数`采购单id`缺失'
        ]);

        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }

        return response()->json(MaterielService::detail($data));
    }

    /**
     * 报溢报损详细
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2023/12/6 17:18
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSpillBreakageInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//报溢报损主单 主键id
        ], [
            'id.required' => '报溢报损主单id缺失'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail($info);
        }
        return success(OverflowBreakageService::commonSearch('', $data));
    }

    /**
     * 操作记录模板（zlf）
     * @param Request $request
     */
    public function logStorageDownload()
    {
        ob_end_clean();

        return response()->download(public_path() . '/log_temp.xlsx', 'log_temp.xlsx');
    }

    public function getApiVersionNo(Request $request)
    {
        return ['code' => 0, 'msg' => 'success', 'data' => ['new_version' => 'https://api.smerp.top/v3.2.7/api', 'old_version' => 'https://api.smerp.top/v3.2.6/api']];
    }

    public function setUserAccount(Request $request)
    {
        DB::beginTransaction();
        try {
            $arr = [];
            $arr['username'] = $request->username;
            $arr['mobile'] = $request->username;
            $arr['created_at'] = time();
            $arr['device'] = 3;
            $arr['bind_id'] = '';
            $arr['is_sync'] = 1;
            $insertId = \App\V3\V3_2_7\Models\AdminModel::insertGetId($arr);
            $vipInfo = VipSettingModel::where('id', 1)->first();
            AdminAddendumModel::insert([
                'main_id' => $insertId,
                'album_amount' => $vipInfo['album_amount'],
                'album_page_amount' => $vipInfo['album_page_amount'],
                'empty_bill_amount' => $vipInfo['empty_bill_amount'],
                'special_seal' => $vipInfo['special_seal'],
                'one_key_album_times' => $vipInfo['one_key_album_times'],
                'express_check_times' => $vipInfo['express_check_times'],
                'account_storage' => $vipInfo['account_storage'],
                'clear_watermark_or_not' => $vipInfo['clear_watermark_or_not'],
                'sub_account_number' => $vipInfo['sub_account_number'],
            ]);
            DB::commit();
            return response()->json(['code' => 0, 'msg' => 'success', 'data' => '']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 1, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    /**
     *货架模板
     * Author: zlf
     * Created at 2024/6/25 14:27
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function shelfDownload(): \Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        ob_end_clean();
        return response()->download(public_path() . '/shelf_temp.xlsx', 'shelf_temp.xlsx');
    }

    /**
     *库位模板
     * Author: zlf
     * Created at 2024/6/25 14:27
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function locationDownload(): \Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        ob_end_clean();
        return response()->download(public_path() . '/location_temp.xlsx', 'location_temp.xlsx');
    }
}
